<?php

namespace app\index\controller;

use think\Loader;
use think\Controller;
use think\Db;
use think\Session;
use think\Exception;
use app\index\model\User;
use app\index\model\News;
use QcloudImage\CIClient;
//Vendor('Qiniu.autoload');
//require 'vendor/Qiniu/autoload.php';


use Qiniu\Auth;


class IndexController extends Controller
{


    /**
     * 验证码图片
     * @param  string $id 验证码ID
     * return string     验证码图片
     */
    public function captcha($id = "")
    {
        $captcha = new \think\captcha\Captcha(config('captcha'));
        return $captcha->entry($id);
    }

    public function index()
    {
        $u = new User();
//        $u->name='reeefr';
//        $u->id=5348;
//        if($u->save()){
//            return '用户 '.$u->name.':'.$u->id.' 新增';
//        }else{
//            return $u->getError();
//        }


//        $list=[['id'=>89,'name'=>'dkk'],['id'=>389,'name'=>'pppw'],['id'=>49,'name'=>'lol']];
//
//        if($u->saveAll($list)){
//            return '批量';
//        }else{
//            return $u->getError();
//        }
        return $this->fetch('index');
        //return "Hello,World!";
        //return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    public function productcenter()
    {
        return $this->fetch('productcenter');
    }

    public function productdetail($id)
    {
        $this->assign('id', $id);
        return $this->fetch('productdetail');
    }

    public function ocr(){

        Loader::addAutoLoadDir('./OCR');

        $appid = '10139867';
        $secretId = 'AKIDHNDn9FEez3rQr3wjCUWIn21jBNK1bmob';
        $secretKey = 'iBQREn7D4g4E9pFPJyNWQ4SaS4RYR5Vg';
        $bucket = 'tac-p44-ho';

        $client = new CIClient($appid, $secretId, $secretKey, $bucket);
        $client->setTimeout(30);
        //单个或多个图片Url
        $js= $client->ocrDetect(array('url'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530718987340&di=781781960ce3e4be591756828d5570ad&imgtype=0&src=http%3A%2F%2Fwww.uqidong.com%2Fuploads%2Fallimg%2F170116%2F183-1F116130125627.png'));
        echo dump(json_decode($js)->data->items[0]->itemstring);

//        return json($client->ocrDetect(array('url'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530718987340&di=781781960ce3e4be591756828d5570ad&imgtype=0&src=http%3A%2F%2Fwww.uqidong.com%2Fuploads%2Fallimg%2F170116%2F183-1F116130125627.png')));
   }
    public function newscenter()
    {
        return $this->fetch();
    }

    public function about()
    {
        return $this->fetch();
    }


    public function favor_plus($id = 0)
    {
        if (!session('user_id')) {
            $data = [
                'value' => 'null',
            ];
            return json($data);
        };

        $n = News::get($id);
        if ($n != null) {
            $n->whofavors()->attach(session('user_id'));

            $n->favor_num = $n->whofavors()->count();
            $data = [
                'value' => '' . $n->favor_num,
            ];
            $n->isUpdate(true)->save();
        } else {
            $data = [
                'value' => '0',
            ];
        }
        return json($data);
    }

    public function favor_minus($id = 0)
    {
        if (!session('user_id')) {
            $data = [
                'value' => 'null',
            ];
            return json($data);
        };

        $n = News::get($id);
        if ($n != null) {

            if ($n->favor_num > 0) {
                $n->whofavors()->detach(session('user_id'));
                $n->favor_num = $n->whofavors()->count();
            }
            $data = [
                'value' => '' . $n->favor_num,
            ];
            $n->isUpdate(true)->save();
        } else {
            $data = [
                'value' => '0',
            ];
        }
        return json($data);
    }

    public function watchdetail($id = 0)
    {

        if ($id > 0) {
            $n = News::get($id);
            if ($n != null) {
                $data = [
                    'title' => '开发中。。。',
                    'cont' => $n->content,
                ];
                $n->watch_num = $n->watch_num + 1;
                $n->isUpdate(true)->save();
            } else {
                $data = [
                    'title' => 'none',
                    'cont' => '<p>none</p>',
                ];
            }
            return json($data);
        }
        return json(['done' => 'ok']);
    }

    public function islogin()
    {
        if (!session('user')) {
            return json(['isLogin' => false]);
        } else {
            return json(['isLogin' => true]);
        }
    }

    public function editor()
    {
        if (!session('user')) {
            $this->assign('URL', '/');
            return $this->fetch('login/login');
        };

        $bucket = config('BUCKET_NAME');
        $accessKey = config('ACCESS_KEY');
        $secretKey = config('SECRET_KEY');

        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        $this->assign('upToken', $upToken);

        return $this->fetch();
    }

    public function upload($img64 = false)
    {
        if ($img64) {
            return json(['file_name' => 'http://cdn.fun100.top/' . $img64]);
        } else {
            return json([]);

        }

//        $base64_image = str_replace(' ', '+', $img64);
//        //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
//        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
//            //匹配成功
//            if($result[2] == 'jpeg'){
//                $image_name = uniqid().'.jpg';
//                //纯粹是看jpeg不爽才替换的
//            }else{
//                $image_name = uniqid().'.'.$result[2];
//            }
//            $image_file = "./upload/test/{$image_name}";
//            //服务器文件存储路径
//            if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
//                return json(['file_name'=>$image_file]);
//            }else{
//                return json(['file_name'=>1]);
//            }
//        }else{
//            return json(['file_name'=>2]);
//        }

    }

    public function upload_html($html, $imgs, $title, $loc)
    {
        $img_paths = '';
        for ($i = 0; $i < count($imgs); $i++) {
            if ($i == count($imgs) - 1) {
                $img_paths = $img_paths . $imgs[$i];
            } else {
                $img_paths = $img_paths . $imgs[$i] . ';';
            }
        }

        $user_id = 1;
        if (session('user_id')) {
            $user_id = session('user_id');
        }
        $u = User::get($user_id);

        $n = new News();
        $n->user_name = $u->tel;
        $n->date = date("Y-m-d h:i:s");
        $n->title = $title;
        $n->content = $html;
        $n->image = $img_paths;
        $n->source = $u->tel;
        $n->location = $loc;
        $n->favor_num = 0;
        $n->watch_num = 0;

        if ($u->writednews()->save($n)) {
            return json(['success' => true]);
        } else {
            return json(['success' => false]);
        }

    }

    public function jsondata2($id = -1)
    {

        $newsfavor = false;
        if (session('user_id')) {
            $user_id = session('user_id');
            $uu = User::get($user_id);
            $newsfavor = $uu->newsfavor()->column('id');
        }


        $count = 16;
        if ($id == -1) {
            $id = Db::query('select max(id) from news')[0]['max(id)'];
        }
        $res = ['count' => $count,];
        try {
            for ($i = 0, $num_id = 0; $num_id < $count; $i++) {
                $idx = $id - $i;

                if ($idx == 0) {
                    $res['count'] = $num_id;
                    return json($res);
                }

                $n = News::get($idx);
                if ($n == null) {
                    continue;
                }
                $trans = '0.5';
                $n_plus = '';

                $imgs = explode(';', $n->image); //存入数组
                $num = count($imgs);

                if ($num > 3) {
                    $n_plus = '+' . ($num - 3);
                } else {
                    $trans = '0';
                }

                $favor_show1 = 'block';
                $favor_show2 = 'none';
                if ($newsfavor && in_array($idx, $newsfavor)) {
                    $favor_show1 = 'none';
                    $favor_show2 = 'block';
                }

                $data = [
                    'idx' => $idx,
                    'trans' => $trans,
                    'num_plus' => $n_plus,
                    'touxiang_url' => $n->author->touxiang,
                    'img_urls' => $n->image,
                    'title' => $n->title,
                    'desc' => $n->source,
                    'user_name' => $n->author->tel,
                    'datetime' => $n->date,
                    'location' => $n->location,
                    'favor' => '' . $n->favor_num,
                    'watch' => '' . $n->watch_num,
                    'favor_show1' => $favor_show1,
                    'favor_show2' => $favor_show2,
                ];

                $res[$num_id] = $data;
                $num_id++;
            }
        } catch (exception $e) {
            return json($res);
        }
//        sleep(0.2);
        return json($res);
    }

    /**
     * @param string $name
     * @return string
     */
    public function hello($name = 'ThinkPHP5')
    {
        echo 'url: ' . $this->request->url();

        //dump($this->request->param());
        echo '<br>' . 'name: ' . $this->request->param('name');
        input('name');
        input('file.image');
//        return 'hello,' . $name;
        $data = ['name' => 'think', 'status' => '1'];
        if (1 == 1) {
//            $this->redirect('thinkphp.cn');
            //$this->success('it\'s ok','index');
        }

        return json($data);

    }

    public function dbtest()
    {
        // $result=Db::execute('create table teacher(id int auto_increment,name varchar(48),primary key (id))');
        //dump($result);
//        try {
//            Db::table('user')->insert(['id' => 6, 'name' => 'pp_think000']);
//
//        } catch (Exception $e) {
//            echo $e;
//        }

//        Db::table('user')->where('id', 3)->update(['name' => 'hhhh']);


        $aa = [1, 2, 3];
//        echo $aa[0];


        return json($aa);


    }

    public function upload_preview()
    {

        $bucket = config('BUCKET_NAME');
        $accessKey = config('ACCESS_KEY');
        $secretKey = config('SECRET_KEY');

        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        $this->assign('upToken', $upToken);

        return $this->fetch();
    }

    public function locate()
    {
        return $this->fetch();
    }

    public function locate2()
    {
        return $this->fetch();
    }

}
